from abc import ABC, abstractmethod
from utils.logger import logger

class ProtocolParser(ABC):
    """协议解析器抽象基类"""
    @abstractmethod
    def parse(self, data: bytes) -> str:
        """解析接收到的原始字节数据"""
        pass

class SimpleTextProtocol(ProtocolParser):
    """简单文本协议解析器"""
    def parse(self, data: bytes) -> str:
        try:
            return data.decode('utf-8').strip()
        except UnicodeDecodeError as e:
            logger.warning(f"解码失败，使用十六进制表示: {e}")
            return f"Binary Data: {data.hex()}"

class ModbusProtocol(ProtocolParser):
    """Modbus协议解析器"""
    def parse(self, data: bytes) -> str:
        if len(data) < 5:  # 至少需要有功能码和数据长度
            return f"Invalid Modbus Packet: {data.hex()}"
        
        address = data[0]
        function = data[1]
        payload = data[2:-2]  # 去除地址和CRC
        crc = data[-2:]
        
        # 简单解析示例（实际应根据功能码解析不同类型的帧）
        if function == 0x03:  # 读保持寄存器
            return f"Modbus(Addr={address}, Func=Read Registers, Data={payload.hex()})"
        elif function == 0x06:  # 写单个寄存器
            return f"Modbus(Addr={address}, Func=Write Register, Data={payload.hex()})"
        else:
            return f"Modbus(Addr={address}, Func=0x{function:02X}, Data={payload.hex()})"